﻿namespace Home.Services.ProductServices
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Globalization;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Http;
    using System.Web.Http.Dispatcher;
    using System.Web.OData;
    using System.Web.OData.Builder;
    using System.Web.OData.Extensions;
    using System.Xml.Linq;
    using Home.Configuration;
    using Home.Data;
    using Home.Models;
    using Owin;

    public static class ProductServiceHelper
    {
        public static void ConfigureProductService(this IAppBuilder app)
        {
            Debug.Assert(app != null);

            //// build EDM model

            var builder = new ODataConventionModelBuilder()
            {
                Namespace = typeof(ProductController).Namespace,
                ContainerName = "DefaultContainer"
            };

            builder.EnumType<DiamondType>();
            builder.EnumType<DiamondShape>();
            builder.EnumType<DiamondClarity>();
            builder.EnumType<DiamondColor>();
            builder.EnumType<DiamondCut>();
            builder.EnumType<DiamondPolish>();
            builder.EnumType<DiamondReport>();
            builder.EnumType<DiamondSymmetry>();
            builder.EnumType<ProductType>();
            builder.EnumType<ProductStatus>();

            {
                var entityType = builder.EntitySet<Diamond>("Diamonds").EntityType;
                IgnoreCommonProperties(entityType);
                entityType.Ignore(c => c.Index);
                entityType.Ignore(c => c.Cost);
                entityType.Ignore(c => c.UploadId);
            }

            var edmModel = builder.GetEdmModel();

            //// configure web API

            var config = new HttpConfiguration();
            if (!ConfigurationHelper.IsProductionEnvironment)
            {
                config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            }
            config.MessageHandlers.Add(new ETagMessageHandler());
            config.MapODataServiceRoute("ProductService", "services/productservice", edmModel);
            config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceAwareHttpControllerSelector(config, typeof(ProductController)));
            config.EnsureInitialized();

            app.UseWebApi(config);
        }

        private static void IgnoreCommonProperties<T>(EntityTypeConfiguration<T> type)
            where T : Entity
        {
            type.Ignore(c => c.Created);
            type.Ignore(c => c.CreatedBy);
            type.Ignore(c => c.Modified);
            type.Ignore(c => c.ModifiedBy);
            type.Ignore(c => c.RowVersion);
        }
    }
}